package com.bw.a2208douyindemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.blankj.utilcode.constant.RegexConstants.REGEX_MOBILE_EXACT
import com.blankj.utilcode.constant.RegexConstants.REGEX_USERNAME
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.a2208douyindemo.MainActivity
import com.bw.a2208douyindemo.databinding.ActivityLoginBinding
import com.bw.base.mvvm.BaseActivity
import com.bw.net.Const
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    override fun initView() {
        if (SPUtils.getInstance().getString(Const.PARAM_LOGIN_USERNAME).isNotEmpty()&&SPUtils.getInstance().getString(Const.PARAM_LOGIN_PASSWORD).isNotEmpty()){
            val user = SPUtils.getInstance().getString(Const.PARAM_LOGIN_USERNAME)
            val pass = SPUtils.getInstance().getString(Const.PARAM_LOGIN_PASSWORD)
            vm.login(pass,user)
        }
        binding.loginBtn.setOnClickListener {
            val user = binding.loginUser.text.toString()
            val pass = binding.loginPass.text.toString()
            if (user.isNotEmpty()&&pass.isNotEmpty()){
                if (!RegexUtils.isMatch(REGEX_MOBILE_EXACT,user)){
                    ToastUtils.showLong("用户名不符合规范")
                    return@setOnClickListener
                }
                if (!RegexUtils.isMatch(REGEX_USERNAME,pass)){
                    ToastUtils.showLong("密码不符合规范")
                    return@setOnClickListener
                }else{
                    vm.login(pass,user)
                }
            }
        }
    }

    override fun initData() {
        vm.loginSuccess.observe(this){
            ToastUtils.showLong("登录成功")
            SPUtils.getInstance().put(Const.TOKEN,it.token)
            SPUtils.getInstance().put(Const.PARAM_LOGIN_USERNAME,it.username)
            SPUtils.getInstance().put(Const.PARAM_LOGIN_PASSWORD,it.password)
            startActivity(Intent(this,MainActivity::class.java))
            finish()
        }
    }
}